package com.mansoor.app.islamicnameslite.services;

import com.mansoor.app.islamicnameslite.beans.Name;
import com.mansoor.app.islamicnameslite.util.AppConstant;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: TKMAQ61
 * Date: Oct 16, 2009
 * Time: 10:54:30 AM
 */
public class RestClientImpl implements RestClient
{
    /**
     * Method getNames ...
     *
     * @param alphabets of type String
     * @param page      of type Integer
     * @return JSONArray
     */
    public List<String> getNames(String alphabets, Integer page) throws IOException, JSONException
    {
        List<String> namearray = new ArrayList<String>();

        final StringBuffer buffer = new StringBuffer();
        final String url = buffer.append(AppConstant.PROD_SERVER).append(AppConstant.NAME_SERVICE).append(AppConstant.ALPHABET).append(AppConstant.SLASH).append(alphabets).append(AppConstant.PAGE).append(AppConstant.SLASH).append(page).toString();
        final String response = sendRequest(url);

        JSONObject json = new JSONObject(response);

        final JSONArray names = json.getJSONArray("names");

        for (int i = 0; i < names.length(); i++)
        {
            final JSONObject record = (JSONObject) names.get(i);
            final String name = record.getString("name");
            namearray.add(name);

        }


        return namearray;  //To change body of implemented methods use File | Settings | File Templates.
    }

    /**
     * Method getNames ...
     *
     * @param alphabets of type String
     * @param gender    of type String
     * @param page      of type Integer
     * @return JSONArray
     */
    public List<String> getNames(String alphabets, String gender, Integer page) throws IOException, JSONException
    {
        List<String> namearray = new ArrayList<String>();

        final StringBuffer buffer = new StringBuffer();
        final String url = buffer.append(AppConstant.PROD_SERVER).append(AppConstant.NAME_SERVICE).append(AppConstant.GENDER).append(AppConstant.SLASH).append(gender).append(AppConstant.ALPHABET).append(AppConstant.SLASH).append(alphabets).append(AppConstant.PAGE).append(AppConstant.SLASH).append(page).toString();
        final String response = sendRequest(url);

        JSONObject json = new JSONObject(response);

        final JSONArray names = json.getJSONArray("names");

        for (int i = 0; i < names.length(); i++)
        {
            final JSONObject record = (JSONObject) names.get(i);
            final String name = record.getString("name");
            namearray.add(name);

        }


        return namearray; //To change body of implemented methods use File | Settings | File Templates.
    }

    public List<Name> getNamesObject(String alphabets, String gender, Integer page) throws IOException, JSONException
    {
        List<Name> namearray = new ArrayList<Name>();

        final StringBuffer buffer = new StringBuffer();
        final String url = buffer.append(AppConstant.PROD_SERVER).append(AppConstant.NAME_SERVICE).append(AppConstant.GENDER).append(AppConstant.SLASH).append(gender).append(AppConstant.ALPHABET).append(AppConstant.SLASH).append(alphabets).append(AppConstant.PAGE).append(AppConstant.SLASH).append(page).toString();
        final String response = sendRequest(url);

        JSONObject json = new JSONObject(response);

        final JSONArray names = json.getJSONArray("names");

        for (int i = 0; i < names.length(); i++)
        {
            final JSONObject record = (JSONObject) names.get(i);
            final String name = record.getString("name");
            Integer id=new Integer(record.getInt("id"));
            String gende=record.getString("gender");
            String meaning=record.getString("meaning");

            Name n= new Name();
            n.setId(id);
            n.setName(name);
            n.setGender(gende);
            n.setMeaning(meaning);
            namearray.add(n);

        }


        return namearray; //To change body of implemented methods use File | Settings | File Templates.
    }

    /**
     * Method getName ...
     *
     * @param name of type String
     * @return JSONObject
     */
    public Name getName(String name) throws IOException, JSONException
    {
        Name result = new Name();

        final StringBuffer buffer = new StringBuffer();
        final String url = buffer.append(AppConstant.PROD_SERVER).append(AppConstant.NAME_SERVICE).append(AppConstant.NAME).append(AppConstant.SLASH).append(URLEncoder.encode(name)).toString();
        final String response = sendRequest(url);

        JSONObject json = new JSONObject(response);

        result.setName(json.getString("name"));
        result.setGender(json.getString("gender"));
        result.setMeaning(json.getString("meaning"));

        return result;
        //To change body of implemented methods use File | Settings | File Templates.
    }

    /**
     * Method count ...
     *
     * @param alphabets of type String
     * @return Integer
     */
    public Integer count(String alphabets) throws IOException, JSONException
    {
        final StringBuffer buffer = new StringBuffer();
        final String url = buffer.append(AppConstant.PROD_SERVER).append(AppConstant.COUNT_SERVICE).append(AppConstant.ALPHABET).append(AppConstant.SLASH).append(alphabets).toString();
        final String response = sendRequest(url);

        Integer count = Integer.parseInt(response);
        return count;  //To change body of implemented methods use File | Settings | File Templates.
    }

    /**
     * Method count ...
     *
     * @param alphabets of type String
     * @param gender    of type String
     * @return Integer
     */
    public Integer count(String alphabets, String gender) throws IOException
    {
        final StringBuffer buffer = new StringBuffer();
        final String url = buffer.append(AppConstant.PROD_SERVER).append(AppConstant.COUNT_SERVICE).append(AppConstant.GENDER).append(AppConstant.SLASH).append(gender).append(AppConstant.ALPHABET).append(AppConstant.SLASH).append(alphabets).toString();
        final String response = sendRequest(url).trim();

        Integer count = Integer.parseInt(response);
        return count; //To change body of implemented methods use File | Settings | File Templates.
    }

    /**
     * Method sendRequest ...
     *
     * @param url of type String
     * @return String
     * @throws IOException when
     */
    private String sendRequest(String url) throws IOException
    {

        HttpClient client = new DefaultHttpClient();
        client.getParams().setIntParameter("http.connection.timeout",new Integer(15 * 1000));
         client.getParams().setIntParameter("http.socket.timeout",new Integer(30 * 1000));
        HttpGet method = new HttpGet(url);

        final HttpResponse response = client.execute(method);

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
        {
            throw new IOException("Connection Failed");
        }

        final InputStream stream = response.getEntity().getContent();

        return this.inputStreamToString(stream);

    }


    /**
     * Method inputStreamToString ...
     *
     * @param stream of type InputStream
     * @return String
     * @throws IOException when
     */
    private String inputStreamToString(final InputStream stream) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(stream));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = br.readLine()) != null)
        {
            sb.append(line + "\n");
        }
        br.close();
        return sb.toString();
    }
}
